package com.heaven.map.security.shiro;

import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.heaven.map.mapper.TAdminMapper;
import com.heaven.map.pojo.po.TAdmin;
import com.heaven.map.security.jwt.JwtToken;
import com.heaven.map.utils.JWTUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ShiroRealm extends AuthorizingRealm {
    @Autowired
    private TAdminMapper tAdminMapper;
    @Autowired
    private JWTUtils jwtUtils;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String token = (String)authenticationToken.getCredentials();
        try {
            String email = jwtUtils.verify(token).getClaim("email").asString();
            TAdmin admin = tAdminMapper.selectOne(new QueryWrapper<TAdmin>().eq("email",email));
            return new SimpleAuthenticationInfo(admin,token,getName());
        }catch (SignatureVerificationException e){
            throw new IncorrectCredentialsException("签名不一致");
        }catch (TokenExpiredException e){
            throw new IncorrectCredentialsException("Token已过期");
        }catch (Exception e){
            throw new IncorrectCredentialsException("无效的签名");
        }
    }
}
